package cn.fl.carloan.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import cmm.comm.facade.upload.constant.SysUlFilesRecConstant;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.carloan.service.IOdrNoticeInfoService;
import cn.fl.carloan.service.IOdrNoticeReadInfoService;
import cn.fl.carloan.transform.OdrNoticeInfoVOTransform;
import cn.fl.carloan.vo.OdrNoticeInfoVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.ref.fncprjbscinfo.util.DateUtil;
import fl.carloan.facade.carloan.dto.OdrNoticeInfoDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

import fl.carloan.facade.carloan.condition.OdrNoticeInfoQC;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;

/**
 * @Description: 公告信息表 控制层
 */
@Controller
@RequestMapping("/carloan/odrnoticeinfo")
public class OdrNoticeInfoController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(OdrNoticeInfoController.class);

    /**
     * OdrNoticeInfo 服务层BEAN
     */
    @Autowired
    private IOdrNoticeInfoService odrNoticeInfoService;

    @Autowired
    private IOdrNoticeReadInfoService odrNoticeReadInfoService;


    /**
     * 到列表页面
     */
    @RequestMapping(value = "/toListPage.do", method = {RequestMethod.GET})
    public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toListPage", "加载列表页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

        ModelAndView view = new ModelAndView("carloan/odrNoticeInfo/odrNoticeInfoList");

        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toListPage", "加载列表页面.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());
        return view;
    }

    /**
     * 到新增修改页面
     */
    @RequestMapping(value = "/toAddPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toAddPage", "加载新增.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

        ModelAndView view = new ModelAndView("carloan/odrNoticeInfo/odrNoticeInfoAdd");

        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toAddPage", "加载新增.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());
        return view;
    }

    /**
     * 到修改页面
     */
    @RequestMapping(value = "/toModifyPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toAddPage", "加载修改页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

        String id = request.getParameter("id");
        OdrNoticeInfoVO noticeInfoVO = null;
        if (StringUtils.isNotEmpty(id)) {
            noticeInfoVO = odrNoticeInfoService.selectById(Long.valueOf(id));
        }
        ModelAndView view = new ModelAndView("carloan/odrNoticeInfo/odrNoticeInfoModify");
        view.addObject("id", id);
        view.addObject("noticeInfoVO", noticeInfoVO);
        view.addObject("serverpath", PropertiesCacheUtils.getProperty(SysUlFilesRecConstant.SYS_FILE_UPLOAD_SERVER_PATH));
        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toAddPage", "加载修改.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());
        return view;
    }

    /**
     * 到详情页面
     */
    @RequestMapping(value = "/toDetailPage.do", method = {RequestMethod.GET})
    public ModelAndView toDetailPage(HttpServletRequest request, HttpServletResponse response) {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toDetailPage", "加载例子详细页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

        String id = request.getParameter("id");
        ModelAndView view = new ModelAndView("carloan/odrNoticeInfo/odrNoticeInfoDetail");
        view.addObject("id", id);

        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toDetailPage", " 加载例子详细页面.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());
        return view;
    }

    /**
     * 初始化列表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initList(HttpServletRequest request, HttpServletResponse response) {
        Long startTm = System.currentTimeMillis();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        BaseLogUtils.info(logger, "initList", "加载列表页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());


        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        String title = request.getParameter("title");
        String label = request.getParameter("label");
        String beginTime = request.getParameter("beginTime");
        String endTime = request.getParameter("endTime");
        Pager page = new Pager();
        OdrNoticeInfoQC qc = new OdrNoticeInfoQC();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }

        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }
        Date beginTimeDate = null;
        if (StringUtils.isNotEmpty(beginTime)) {
            Date dateByStringTime = DateUtil.getDateByStringTime(beginTime);
            String format = sdf.format(dateByStringTime);
            try {
                beginTimeDate = sdf.parse(format);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            qc.setBeginTime(beginTimeDate);
        }
        Date endTimeData = null;
        if (StringUtils.isNotEmpty(endTime)) {
            Date dateByStringTime = DateUtil.getDateByStringTime(endTime);
            String format = sdf.format(dateByStringTime);
            try {
                endTimeData = sdf.parse(format);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            qc.setEndTime(endTimeData);
        }

        qc.setTitle(title);
        qc.setLabel(label);
        qc.setIsDel(0);
        page.setCondition(qc);
        Pager pager = new Pager();
        pager = this.odrNoticeInfoService.searchListPage(page);
        List<OdrNoticeInfoDTO> list = (List<OdrNoticeInfoDTO>) pager.getResultList();
        if (CollectionUtils.isNotEmpty(list)) {
            for (int i = 0; i < list.size(); i++) {
                if (1 == list.get(i).getIsTop()) {
                    list.add(0, list.get(i));
                    list.remove(i + 1);
                }
            }
        }
        ListPageVO<OdrNoticeInfoVO> listPage = new ListPageVO<OdrNoticeInfoVO>(OdrNoticeInfoVOTransform.toVOList(list), pager.getTotalCount());
        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "initList", "加载列表页面.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());
        return listPage;
    }

    /**
     * 新增
     */
    @RequestMapping(value = "/add.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "add", "新增对象.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

        String name = request.getParameter("name");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "新增成功!");
        OdrNoticeInfoVO entity = null;
        try {
            entity = new OdrNoticeInfoVO();
            //TODO ADD PARAM
            Long id = this.odrNoticeInfoService.add(entity);
            result.setData(id);
            BaseLogUtils.info(logger, "add", "新增数据.[id=" + id + "] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "add", "新增对象失败,name[" + name + "].", CurrentThreadContext.getCurrentUserName(), ex);
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("系统错误,请联系管理员!");
            BaseLogUtils.error(logger, "add", "新增对象失败,name[" + name + "].", CurrentThreadContext.getCurrentUserName(), ex);
        }
        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "add", "新增对象.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());

        return result;
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/modify.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "modify", "修改对象.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

        String id = request.getParameter("noticeId");
        String title = request.getParameter("title");
        String label = request.getParameter("label");
        String isTop = request.getParameter("isTop");
        String notice_Content = request.getParameter("notice_Content");
        String isDel = request.getParameter("isDel");
        String noticeDesc = request.getParameter("noticeDesc");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "修改成功!");
        if (StringUtils.isEmpty(id)) {
            OdrNoticeInfoVO noticeInfoVO = new OdrNoticeInfoVO();
            noticeInfoVO.setIsDel(0);
            noticeInfoVO.setCrtTm(new Date());
            noticeInfoVO.setMdfTm(new Date());
            if (StringUtils.isNotEmpty(isTop)) {
                noticeInfoVO.setIsTop(Integer.valueOf(isTop));
            }
            noticeInfoVO.setLabel(label);
            noticeInfoVO.setTitle(title);
            noticeInfoVO.setNoticeContent(notice_Content);
            noticeInfoVO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
            if (StringUtils.isEmpty(noticeDesc)||StringUtils.isEmpty(title)||StringUtils.isEmpty(notice_Content)) {
                result.setSuccess(0);
                result.setInfo("公告标题、描述、内容不能为空！");
                return result;
            }
            noticeInfoVO.setPictUrl(noticeDesc);
            BaseLogUtils.info(logger, "add", "新增一条公告 参数--》" + JSONObject.toJSONString(noticeInfoVO), CurrentThreadContext.getCurrentUserName());

            try {
                Long add = odrNoticeInfoService.add(noticeInfoVO);
                result.setSuccess(1);
                result.setInfo("新增公告成功！");
                result.setData(add);
                return result;
            } catch (BaseException e) {
                BaseLogUtils.info(logger, "add", "新增公告失败", CurrentThreadContext.getCurrentUserName());
                e.printStackTrace();
                result.setSuccess(0);
                result.setInfo("新增公告失败！");
                return result;
            }


        }
        OdrNoticeInfoVO entity = null;
        try {
            entity = new OdrNoticeInfoVO();
            entity.setId(Long.valueOf(id));
            entity.setMdfTm(new Date());
            if (StringUtils.isNotEmpty(isTop)) {
                entity.setIsTop(Integer.valueOf(isTop));
                odrNoticeInfoService.removeAllTop();
            }
            entity.setNoticeContent(notice_Content);
            entity.setLabel(label);
            entity.setTitle(title);
            entity.setPictUrl(noticeDesc);
            if (StringUtils.isNotEmpty(isDel)) {
                entity.setIsDel(Integer.valueOf(isDel));
            }
            boolean success = this.odrNoticeInfoService.modify(entity);
           // odrNoticeReadInfoService.removeByNoticeId(Long.valueOf(id));
            if (!success) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("修改失败!");
                BaseLogUtils.info(logger, "modify", "修改失败.[id=" + id + "] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
            }
            BaseLogUtils.info(logger, "modify", "修改成功.[id=" + id + "] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "modify", "修改对象失败,id[" + id + "].", CurrentThreadContext.getCurrentUserName(), ex);
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("系统错误,请联系管理员!");
            BaseLogUtils.error(logger, "modify", "修改对象失败,id[" + id + "].", CurrentThreadContext.getCurrentUserName(), ex);
        }

        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "modify", "修改对象.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());

        return result;
    }

    /**
     * 删除数据
     */
    @RequestMapping(value = "/removeById.do", method = {RequestMethod.POST})
    @ResponseBody
    public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "remove", "移除对象.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

        String id = request.getParameter("id");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "删除成功!");
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("主键不能为空!");
            return result;
        }
        try {
            this.odrNoticeInfoService.removeById(Long.valueOf(id));
            BaseLogUtils.info(logger, "removeById", "删除数据.[id=" + id + "]", CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "remove", "移除对象失败,主键[" + id + "].", CurrentThreadContext.getCurrentUserName(), ex);
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("系统错误,请联系管理员!");
            BaseLogUtils.error(logger, "remove", "移除对象失败,主键[" + id + "].", CurrentThreadContext.getCurrentUserName(), ex);
        }

        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "remove", "移除对象.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());

        return result;
    }

    /**
     * 得到一条记录
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getById.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "getById", "根据主键获取对象.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

        String id = request.getParameter("id");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "操作成功!");
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("主键不能为空!");
            BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id=" + id + "]", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        try {
            OdrNoticeInfoVO vo = this.odrNoticeInfoService.selectById(Long.valueOf(id));
            if (null == vo) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("数据不存在!");
                BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id=" + id + "]", CurrentThreadContext.getCurrentUserName());
            }
            result.setData(vo);
            BaseLogUtils.info(logger, "getById", "获取数据.[id=" + id + "]", CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "getById", "根据主键获取对象失败,主键[" + id + "].", CurrentThreadContext.getCurrentUserName(), ex);
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("系统错误,请联系管理员!");
            BaseLogUtils.error(logger, "getById", "根据主键获取对象失败,主键[" + id + "].", CurrentThreadContext.getCurrentUserName(), ex);
        }

        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "getById", "根据主键获取对象.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());

        return result;
    }

}

